<template>
    <el-dialog v-model="showDialog" :title="'调整' + currentTitle" width="550px" :destroy-on-close="true">
        <el-form :model="formData" label-width="110px" ref="formRef" :rules="formRules" class="page-form" v-loading="loading" @submit.enter.prevent>

            <el-form-item :label="'当前' + currentTitle" >
                <div v-if="type == 1" class="input-width"> {{ formData.contribution_points }} </div>
                <div v-if="type == 2" class="input-width"> {{ formData.available_points }} </div>
                <div v-if="type == 3" class="input-width"> {{ formData.gold_coupon }} </div>
                <div v-if="type == 4" class="input-width"> {{ formData.digital_asset }} </div>
            </el-form-item>

            <el-form-item :label="t('adjustType')">
                <el-radio-group v-model="formData.adjust_type">
                    <el-radio :label="1">{{ t('adjustAddPoint') }}</el-radio>
                    <el-radio :label="-1">{{ t('adjustReducePoint') }}</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item :label="'调整' + currentTitle" prop="adjust">
                <el-input-number
                    v-model="formData.adjust"
                    clearable
                    :min="0"
                    :max="9999999"
                    :precision="2"
                    :step="0.01"
                    :placeholder="t('adjustPlaceholder')"
                    @focus="formData.adjust = ''"
                    class="!w-[200px]"
                />
            </el-form-item>

            <el-form-item :label="t('memo')" prop="memo">
                <el-input v-model.trim="formData.memo" type="textarea" rows="4" clearable :placeholder="t('memoPlaceholder')" class="input-width"/>
            </el-form-item>

        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="showDialog = false">{{ t('cancel') }}</el-button>
                <el-button type="primary" :loading="loading" @click="confirm(formRef)">{{t('confirm')}}</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import { t } from '@/lang'
import type { FormInstance } from 'element-plus'
import { adjustGoldPoints, adjustPoints } from '@/app/api/member'

const showDialog = ref(false)
const loading = ref(true)
const repeat = ref(false)

const props = defineProps({
    type: {
        type: [String, Number],
        default: 1
    },
})

const currentTitle = computed(() => {
    if (props.type == 1) {
        return '贡献值'
    } else if (props.type == 2) {
        return '可用积分'
    } else if (props.type == 3) {
        return '兑换券'
    } else if (props.type == 4) {
        return '星星豆'
    } else {
        return ''
    }
})

/**
 * 表单数据
 */
const initialFormData = {
    member_id: 0,
    adjust_type: 1, // 1: 增加  -1: 减少
    adjust: 0, // 增加或减少的积分数
    memo: '', // 备注
    contribution_points: 0, // 贡献值
    available_points: 0, // 可用积分
    gold_coupon: 0, // 兑换券
    digital_asset: 0, // 星星豆
}
const formData: Record<string, any> = reactive({ ...initialFormData })

const formRef = ref<FormInstance>()

// 表单验证规则
const formRules = computed(() => {
    return {
        adjust: [
            { required: true, message: t('adjustPointPlaceholder'), trigger: 'blur' },
            {
                validator: (rule: any, value: string, callback: any) => {
                    if (formData.adjust !== '' && formData.adjust !== null && formData.adjust !== undefined) {
                        const numericValue = parseFloat(formData.adjust)
                        if (!isNaN(numericValue)) {
                            formData.adjust = Number(numericValue.toFixed(2))
                        }
                    }

                    const adjust = Math.abs(parseFloat(formData.adjust))

                    if (!adjust) {
                        callback(new Error(t('adjustPointPlaceholder')))
                    }
                    let point = null;
                    if (props.type == 1) {
                        point = formData.contribution_points
                    } else if (props.type == 2) {
                        point = formData.available_points
                    } else if (props.type == 3) {
                        point = formData.gold_coupon
                    } else if (props.type == 4) {
                        point = formData.digital_asset
                    }
                    if (formData.adjust_type == -1 && (parseFloat(point) - adjust < 0)) {
                        callback(new Error(t('adjustPointMaxAccountMessage')))
                    }

                    callback()
                },
                trigger: 'blur'
            }
        ]
    }
})

/**
 * 确认
 * @param formEl
 */
const confirm = async (formEl: FormInstance | undefined) => {
    if (loading.value || !formEl) return

    await formEl.validate(async (valid) => {
        if (valid) {
            loading.value = true

            if (repeat.value) return
            repeat.value = true
            let data = Object.assign({}, formData)
            if (props.type == 1) {
                data.contribution_points = Math.abs(parseFloat(formData.adjust)) * formData.adjust_type
                delete data.available_points
                delete data.gold_coupon
                delete data.digital_asset
            } else if (props.type == 2) {
                data.available_points = Math.abs(parseFloat(formData.adjust)) * formData.adjust_type
                delete data.contribution_points
                delete data.gold_coupon
                delete data.digital_asset
            } else if (props.type == 3) {
                data.gold_coupon = Math.abs(parseFloat(formData.adjust)) * formData.adjust_type
                delete data.contribution_points
                delete data.available_points
                delete data.digital_asset
            } else if (props.type == 4) {
                data.digital_asset = Math.abs(parseFloat(formData.adjust)) * formData.adjust_type
                delete data.contribution_points
                delete data.available_points
                delete data.gold_coupon
            }
            delete data.adjust
            let request = props.type == 3 ? adjustGoldPoints : adjustPoints
            request(data).then(res => {
                loading.value = false
                repeat.value = false
                showDialog.value = false
                emit('complete')
            }).catch(() => {
                loading.value = false
                repeat.value = false
                // showDialog.value = false
            })
        }
    })
}

const emit = defineEmits(['complete'])

const setFormData = async (row: any = null) => {
    loading.value = true
    Object.assign(formData, initialFormData)
    if (row) {
        Object.keys(formData).forEach((key: string) => {
            if (row[key] != undefined) formData[key] = row[key]
        })
    }
    loading.value = false
}

defineExpose({
    showDialog,
    setFormData
})
</script>

<style lang="scss" scoped></style>
